import React, { useState, useEffect } from 'react';
import { Button, Spin, Alert, Typography,Table } from 'dingtalk-design-desktop';
import type { ColumnsType, FilterValue, SorterResult } from 'dingtalk-design-desktop/es/table/interface';


const FinanceList: React.FC = () => {
  const [curRates, setCurRates] = useState<CurrencyRate[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);


  // 使用 fetch 获取数据的函数
  const fetchCurrencyRates = async (forceUpdate: boolean = false) => {
    setLoading(true);
    setError(null);
    try {
      //      http://127.0.0.1:8288
      let url=`https://www.treetask.cn/dingtool/api/currency_rate/cur`+(forceUpdate?`?forceUpdate=1`:'');
      const response = await fetch(url);
      if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
      }
      const data = await response.json();
      setCurRates(data?.data); //
    } catch (err) {
      // 处理错误
      setError(`错误`);
    } finally {
      setTimeout(() => {
        setLoading(false);
      }, 300);
    }
  };
    const columns: ColumnsType<CurrencyRate> = [
     {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      width: 80,
      ellipsis: true,
    },
     {
      title: '中行卖出价',
       dataIndex: 'sale',
      width: 150,
      key: 'sale',
      ellipsis: true,
    },
    {
      title: '海关汇率',
      dataIndex: 'value',
      width: 150,
      key: 'value',
      ellipsis: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      ellipsis: true,
      },
      {
      title: '更新时间',
      dataIndex: 'createTime',
      key: 'createTime',
      ellipsis: true,
    },
  ];

  // 组件挂载时获取数据
  useEffect(() => {
    fetchCurrencyRates(false);
  }, []);

  return (
    <div style={{ padding: '20px' }}>
      
        <div>
          <Button 
            type="primary" 
            onClick={()=>fetchCurrencyRates()}
            style={{ marginBottom: '16px' }}
          >
            刷新
          </Button>
          <Button 
            type="primary" 
            onClick={()=>fetchCurrencyRates(true)}
            style={{ marginBottom: '16px',marginLeft:'15px' }}
          >
            强制刷新
        </Button>
      </div>
      {error && (
        <Alert 
          type="error" 
          message="错误" 
          description={
            <div>
               {error}
            </div>
          } 
          closable 
          onClose={() => setError(null)} 
        />
      )}
      {!error && (
      <Spin size="default" spinning={loading} >
        <Table 
            columns={columns} 
            dataSource={curRates} 
            rowKey="id"
          />
        </Spin>
      )}
    </div>
  );
};

export default FinanceList;